package com.cxs.controller;

import cn.hutool.core.map.MapUtil;
import com.cxs.common.dto.MenuDto;
import com.cxs.common.lang.Const;
import com.cxs.controller.base.BaseController;
import com.cxs.entity.Permission;
import com.cxs.entity.User;
import com.cxs.mapper.PermissionMapper;
import com.cxs.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chaoxiaoshu
 * @since 2022-06-08
 */
@RestController
@RequestMapping("/sys/menu")
public class PermissionController extends BaseController {

    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 获取当前用户的菜单栏以及权限
     * Principal principal表示注入当前用户的信息，getName就可以获取当当前用户的用户名了。
     * @return
     */
    @GetMapping("/nav")
    public Map<Object, Object> getNav(Principal principal) {
        String username = principal.getName();
        User user = userService.getByUsername(username);
        if (redisUtil.hHasKey(Const.CACHE_KEY_NAV, username)) {
            return (Map<Object, Object>) redisUtil.hget(Const.CACHE_KEY_NAV, username);
        } else {
            // ROLE_Admin,sys:user:save
            String[] authoritys = StringUtils.tokenizeToStringArray(permissionService.getAuthorityByUserId(user.getId()), ",");
            List<MenuDto> nav = permissionService.getMenu(user.getId());
            Map<Object, Object> map = MapUtil.builder()
                    .put("nav", nav)
                    .put("authoritys", authoritys)
                    .map();
            redisUtil.hset(Const.CACHE_KEY_NAV, username, map);
            return map;
        }
    }

    // 根据权限id获取权限信息
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Permission info(@PathVariable("id") Long id) {
        return permissionService.getById(id);
    }


    /**
     * 获取所有权限列表
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public List<Permission> list() {
        List<Permission> perms = permissionService.buildTree(permissionService.list());
        return perms;
    }

    @PostMapping("/getMenu")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public List<Permission> getMenu() {
        List<Permission> perms = permissionService.findAllMenu(new int[] {Const.MENU_TYPE_MENU});
        return perms;
    }

    /**
     * 添加权限
     * @param permission
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public boolean save(@Validated @RequestBody Permission permission) {
        return permissionService.save(permission);
    }

    /**
     * 更新权限并删除关联的用户的缓存
     * @param permission
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Permission update(@Validated @RequestBody Permission permission) {
        permissionService.updateById(permission);
        // 清除所有与该菜单相关联的用户的权限缓存
        permissionService.clearCacheByPermissionId(permission.getId());
        return permission;
    }

}
